import express from "express";
import bodyParser from "body-parser";
import cors from "cors";
import morgan from "morgan";
import clipboardy from "clipboardy";
import * as CDN from "./cdn";
import { hash } from "./utils";
import https from "https";
import {
  CDN_HOST,
  OSS_ACCESS_KEY_ID,
  OSS_ACCESS_KEY_SECRET,
  PORT,
} from "./env";

const app = express();

app.use(cors());
app.use(morgan("short"));

app.get("/download", async (req, res) => {
  try {
    const url = req.query.url as string;
    const svg = await http(url);
    let cleanSvg = svg!;
    if (cleanSvg.startsWith('"') && cleanSvg.endsWith('"')) {
      cleanSvg = cleanSvg.slice(1, -1);
    }
    // 替换转义的引号和反斜杠
    cleanSvg = cleanSvg
      .replace(/\\"/g, '"')
      .replace(/\\'/g, "'")
      .replace(/\\\\/g, "\\");
    const buffer = Buffer.from(cleanSvg);
    res
      .status(200)
      .set({
        "Content-Type": "image/svg+xml",
        "Content-Disposition": "inline",
        "Cache-Control": "public, max-age=3600",
        "X-Content-Type-Options": "nosniff",
      })
      .end(buffer);
  } catch (error) {
    console.error(error);
    res.status(500).end();
  }
});

app.get("/:digest", async (req, res) => {
  try {
    const digest = req.params.digest;
    await Promise.all([
      CDN.isFileExisted(digest + ".svg"),
      // CDN.isFileExisted(digest + '.svg.encoded'),
    ]);
    res.end();
  } catch (err) {
    res.status(404).end();
  }
});
app.post("/upload", bodyParser.text(), async (req, res) => {
  try {
    const svg = req.body + "";
    const digest = hash(svg);
    const buffer = Buffer.from(svg);
    const encoded = Buffer.from(
      "data:image/svg+xml;base64," + buffer.toString("base64")
    );
    await Promise.all([
      CDN.uploadFile(digest + ".svg", buffer),
      // CDN.uploadFile(digest + '.svg.encoded', encoded),
    ]);

    res.end();
  } catch (err) {
    res
      .status(500)
      .json({ err: err + "" })
      .end();
  }
});

app.post("/digest", bodyParser.text(), async (req, res) => {
  try {
    const svg = req.body + "";
    const digest = hash(svg);
    res.send(digest);
  } catch (err) {
    res
      .status(500)
      .json({ err: err + "" })
      .end();
  }
});

app.post("/copy", bodyParser.text(), (req, res) => {
  clipboardy
    .write(req.body)
    .then(() => res.end())
    .catch((err) => {
      console.error(err);
      res.status(500).end();
    });
});

app.listen(PORT, () => {
  console.log(`Figma Developer Helper Server is running on PORT ${PORT}`);
});

const http = (url: string) => {
  return fetch(url)
    .then((response) => response.text())
    .catch((error) => {
      console.error(error);
    });
};
